package member

import (
	"dhfshop/models/member"
	"time"
	"strconv"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego/validation"
)

type DeliveryController struct {
	base.BaseController
}

// 地址管理
func (this *DeliveryController) DeliveryList() {
	query,_,fields,order_by,offset,limit,err := this.GetQueryPara()
	if err != nil {
	   this.ServeError(err.Error())
	   return
	}
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	query["member_id"] = strconv.FormatInt(curUserId, 10)
	l, _, err := member.GetAllDeliverAddrs(query,fields,order_by,offset,limit)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	r := struct {
	       TotalCount     int64                  `json:"total_count"`
	       DeliverAddrs   []*member.DeliverAddr  `json:"deliver_addrs"`
	    }{TotalCount: 0, DeliverAddrs: l}
	this.Data["json"] = r
	this.ServeJSON()
}

func (this *DeliveryController) Post() {
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	if curUserId == 0 {
	    this.ServeError("user is not login")
	    return
	}
	var v member.DeliverAddr
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.Address, "address")
	valid.Required(v.Mobile, "mobile")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	v.MemberId = int64(curUserId)
	if defaultAddr, err := member.GetDefaultAddrByMemberId(v.MemberId); err == nil {
		if v.IsDefault == 1 {
		    defaultAddr.IsDefault = 0
		    member.UpdateDeliver(defaultAddr, "is_default")   //去掉老的地址的缺省设置
			addressId, err := member.AddDeliver(&v)
	        if err != nil {
		        this.ServeError(err.Error())
		        return
	        }
	        v.AddressId = addressId
		}else{
		    addressId, err := member.AddDeliver(&v)
	        if err != nil {
		        this.ServeError(err.Error())
		        return
	        }
	        v.AddressId = addressId
		}	
	}else{
	    v.IsDefault = 1
	    addressId, err := member.AddDeliver(&v)
	    if err != nil {
		    this.ServeError(err.Error())
		    return
	    }
	    v.AddressId = addressId
	}
	rsp := struct {
		AddressId int64      `json:"address_id"`
	    Created   time.Time  `json:"created"`
	}{AddressId: v.AddressId, Created:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *DeliveryController) Put() {
	var v member.DeliverAddr
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.AddressId, "address_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	excludeArr := []string{""}
	updateFields, err := this.GetUpdateFields(v, "", "form", excludeArr)
	if err != nil {
	   this.ServeError(err.Error())
		return
	}
	oldvalue, err := member.GetDeliverAddrById(v.AddressId)
	if err != nil{
		this.ServeError(err.Error())
		return
	}
	if (v.IsDefault == 1) && (oldvalue.IsDefault == 0) {   //只能增加为缺省
		if defaultAddr, err := member.GetDefaultAddrByMemberId(oldvalue.MemberId); err == nil {
		    defaultAddr.IsDefault = 0
			member.UpdateDeliver(defaultAddr, "is_default")   //去掉老的地址的缺省设置
		}
	}
	if len(updateFields) > 0 {
		if _, err := member.UpdateDeliver(&v, updateFields...); err != nil{
		    this.ServeError(err.Error())
		    return
	    }	
	}
	rsp := struct {
		    AddressId int64       `json:"address_id"`
	        Modified  time.Time   `json:"modified"`
	    }{AddressId:v.AddressId, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}


func (this *DeliveryController) Delete() {
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	if curUserId == 0 {
	     this.ServeError("user is not login")
	    return
	}
	addressId, err := this.GetInt("address_id")
	if err != nil {
	    this.ServeError(err.Error())
	    return
	}
	deliverAddr, err := member.GetDeliverAddrById(int64(addressId))
	if err != nil {
	    this.ServeError(err.Error())
	    return
	}
	if err := member.DeleteDeliver(int64(addressId)); err != nil {
	    this.ServeError(err.Error())
	    return
	}
	if deliverAddr.IsDefault == 1 {
	    list, err := member.GetAllDeliverAddr(curUserId)
	    if err != nil {
	        this.ServeError(err.Error())
	        return
	    } 
		list[0].IsDefault = 1
		member.UpdateDeliver(list[0], "is_default")  
	}
    r := struct {
		    AddressId int         `json:"address_id"`
	        Modified  time.Time   `json:"modified"`
	    }{AddressId:addressId, Modified:time.Now().UTC()}
	this.Data["json"] = r 
	this.ServeJSON()
}
